﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace 账号管理
{
    public class XSerialize
    {
        public static void SerializeToFile<T>(T data, string fileName)
        {
            var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            try
            {
                var binarySerializer = new BinaryFormatter();
                binarySerializer.Serialize(fs, data);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

        public static T DeserializeFromFile<T>(string fileName)
        {
            if (!System.IO.File.Exists(fileName))
            {
                return default(T);
            }
            var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            try
            {
                object obj = null;
                var binarySerializer = new BinaryFormatter();
                obj = binarySerializer.Deserialize(fs);
                return (T)obj;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
    }
}
